package com.huayu.languo.common.configurer;


import com.huayu.languo.common.constant.OrderConstant;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/** FIXME
 * @desc 接口响应体处理器
 */
@Order(OrderConstant.API_GLOBAL_RESPONSE_ORDER)
//@ControllerAdvice(basePackages = AppConstants.SWAGGER_SCAN_BASE_PACKAGE) // api接口 响应内容再次封装
@Component
public class AppResponseAdvice implements ResponseBodyAdvice<Object> {

    public static final String RESPONSE_RESULT = "RESPONSE-RESULT";

    public static final String RQUEST_URI = "RQUEST_URI";

    public static final String API_PRE = "/api/";


    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //  这个先 走 还是 全局异常先走
        System.out.println("AppResponseAdvice  这个先 走 还是 全局异常先走 ");



        // 有需要增强的注解的类
        //ResponseResult responseResultAnn = (ResponseResult) RequestContextHolderUtil.getRequest().getAttribute(RESPONSE_RESULT);
        //if (responseResultAnn != null) {
        //    return true;
        //}

        // 请求URI里有api的类
        //String requestUri = (String) RequestContextHolderUtil.getRequest().getAttribute(RQUEST_URI);
        //if (!StringUtils.isEmpty(requestUri) && requestUri.startsWith(API_PRE)) {
        //    return true;
        //}

        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        // 在此处对 请求结果做增强。可以在 json体 外再包装一层
        // 在响应头里添加 版本信息，token等等
        // 设置响应体 编码 格式

        //body 是 model and view 直接返回, 或者 arePage threadLocal

        return body;
    }
}
